// 会员服务，处理充值、会员购买等功能
import { authService } from './auth.js'

// 会员套餐定义
export const MEMBERSHIP_PLANS = {
  MONTHLY: {
    id: 'monthly',
    name: '月度会员',
    price: 30,
    duration: 30, // 天数
    description: '30天会员特权，享受所有高级功能'
  },
  QUARTERLY: {
    id: 'quarterly',
    name: '季度会员',
    price: 80,
    duration: 90,
    description: '90天会员特权，享受所有高级功能，节省10%'
  },
  YEARLY: {
    id: 'yearly',
    name: '年度会员',
    price: 298,
    duration: 365,
    description: '365天会员特权，享受所有高级功能，节省20%'
  }
}

// 充值套餐定义
export const RECHARGE_PLANS = [
  { amount: 10, coins: 100 },
  { amount: 30, coins: 350 }, // 额外赠送50金币
  { amount: 50, coins: 600 }, // 额外赠送100金币
  { amount: 100, coins: 1300 }, // 额外赠送300金币
  { amount: 200, coins: 2800 } // 额外赠送800金币
]

export const membershipService = {
  // 获取当前用户会员状态
  getCurrentMembershipStatus() {
    const user = authService.getCurrentUser()
    if (!user) return null
    
    return {
      isMember: user.isMember || false,
      memberExpiry: user.memberExpiry,
      daysRemaining: user.isMember && user.memberExpiry ? 
        Math.ceil((new Date(user.memberExpiry) - new Date()) / (1000 * 60 * 60 * 24)) : 0
    }
  },

  // 充值金币
  async recharge(userId, amount) {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 验证金额是否有效
    const plan = RECHARGE_PLANS.find(p => p.amount === amount)
    if (!plan) {
      throw new Error('无效的充值金额')
    }
    
    // 获取用户信息
    const user = authService.getUserById(userId)
    if (!user) {
      throw new Error('用户不存在')
    }
    
    // 更新用户余额
    const newBalance = (user.balance || 0) + plan.coins
    const updatedUser = authService.updateUser(userId, { balance: newBalance })
    
    // 记录充值历史（模拟）
    this._recordTransaction(userId, 'recharge', plan.coins, amount)
    
    return {
      success: true,
      newBalance,
      coinsAdded: plan.coins,
      amountPaid: amount
    }
  },

  // 购买会员
  async purchaseMembership(userId, planId) {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 获取套餐信息
    const plan = MEMBERSHIP_PLANS[planId]
    if (!plan) {
      throw new Error('无效的会员套餐')
    }
    
    // 获取用户信息
    const user = authService.getUserById(userId)
    if (!user) {
      throw new Error('用户不存在')
    }
    
    // 检查余额是否足够
    if ((user.balance || 0) < plan.price) {
      throw new Error('金币余额不足，请先充值')
    }
    
    // 计算新的到期时间
    const now = new Date()
    let newExpiryDate
    
    if (user.isMember && user.memberExpiry) {
      // 如果已有会员，累加天数
      const currentExpiry = new Date(user.memberExpiry)
      newExpiryDate = new Date(currentExpiry.getTime() + plan.duration * 24 * 60 * 60 * 1000)
    } else {
      // 新会员，从现在开始计算
      newExpiryDate = new Date(now.getTime() + plan.duration * 24 * 60 * 60 * 1000)
    }
    
    // 更新用户信息
    const newBalance = user.balance - plan.price
    const updatedUser = authService.updateUser(userId, {
      isMember: true,
      memberExpiry: newExpiryDate.toISOString(),
      balance: newBalance
    })
    
    // 记录交易历史（模拟）
    this._recordTransaction(userId, 'membership_purchase', -plan.price, plan.price)
    
    return {
      success: true,
      plan,
      newExpiryDate,
      daysAdded: plan.duration,
      coinsSpent: plan.price,
      remainingBalance: newBalance
    }
  },

  // 模拟记录交易历史
  _recordTransaction(userId, type, coinsChange, amount) {
    // 在实际应用中，这里应该调用API保存到服务器
    // 现在我们只是在控制台打印信息
    console.log('交易记录:', {
      userId,
      type,
      coinsChange,
      amount,
      timestamp: new Date().toISOString()
    })
    
    // 简单地将交易记录保存到localStorage
    const transactions = JSON.parse(localStorage.getItem('pubg_guide_transactions') || '[]')
    transactions.push({
      id: `tx_${Date.now()}`,
      userId,
      type,
      coinsChange,
      amount,
      timestamp: new Date().toISOString()
    })
    localStorage.setItem('pubg_guide_transactions', JSON.stringify(transactions))
  },

  // 获取用户交易历史（模拟）
  getUserTransactions(userId) {
    const allTransactions = JSON.parse(localStorage.getItem('pubg_guide_transactions') || '[]')
    return allTransactions.filter(tx => tx.userId === userId).reverse()
  }
}